package com.project;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.*;

import jakarta.servlet.http.HttpSession;

@WebServlet("/GetTicketsServlet")
public class GetTicketsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("GetTicketsServlet");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        DB_Ticket dbTicket = new DB_Ticket();
        DB_Order dbOrder = new DB_Order();
        DB_Airline dbAirline = new DB_Airline();
        DB_Flight dbFlight = new DB_Flight();

        // 查询用户的所有机票
        List<String> ticketConditions = new ArrayList<>();
        ticketConditions.add("uid=" + user.getUid());
        List<String> tickets = dbTicket.find(ticketConditions);
        if (tickets.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        List<String> resultTickets = new ArrayList<>();
        for (String ticketStr : tickets) {
            String[] ticketInfo = ticketStr.split(",");
            String oid = ticketInfo[4].equals("1") ? "已取票" : ticketInfo[1];

            // 查询订单信息
            List<String> orderConditions = new ArrayList<>();
            orderConditions.add("oid=" + oid);
            List<String> orders = dbOrder.find(orderConditions);
            if (orders.isEmpty()) {
                continue;
            }
            String[] orderInfo = orders.getFirst().split(",");
            String aid = orderInfo[2];
            String State = orderInfo[5];

            // 查询航线信息
            List<String> airlineConditions = new ArrayList<>();
            airlineConditions.add("aid=" + aid);
            List<String> airlines = dbAirline.find(airlineConditions);
            if (airlines.isEmpty()) {
                continue;
            }
            String[] airlineInfo = airlines.getFirst().split(",");
            String fid = airlineInfo[1];

            // 查询航班信息
            List<String> flightConditions = new ArrayList<>();
            flightConditions.add("fid=" + fid);
            List<String> flights = dbFlight.find(flightConditions);
            if (flights.isEmpty()) {
                continue;
            }
            String[] flightInfo = flights.getFirst().split(",");

            // 组合机票信息
            String ticketData = ticketInfo[0] + "," + // 机票id
                    oid + "," + // 订单id
                    ticketInfo[2] + "," + // 用户id
                    ticketInfo[3] + "," + // 座位
                    State + "," + // 状态
                    flightInfo[1] + "," + // 起飞时间
                    flightInfo[2] + "," + // 到达时间
                    flightInfo[3] + "," + // 起飞站
                    flightInfo[4] + "," + // 到达站
                    flightInfo[5] + "," + // 登机时间
                    airlineInfo[3]; // 席别

            resultTickets.add(ticketData);
        }

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        StringBuilder jsonResponse = new StringBuilder();
        jsonResponse.append("{\"tickets\":[");
        for (int i = 0; i < resultTickets.size(); i++) {
            String[] ticketFields = resultTickets.get(i).split(",");
            jsonResponse.append("{");
            jsonResponse.append("\"id\":\"").append(ticketFields[0]).append("\",");
            jsonResponse.append("\"oid\":\"").append(ticketFields[1]).append("\",");
            jsonResponse.append("\"uid\":\"").append(ticketFields[2]).append("\",");
            jsonResponse.append("\"seat\":\"").append(ticketFields[3]).append("\",");
            jsonResponse.append("\"state\":\"").append(ticketFields[4]).append("\",");
            jsonResponse.append("\"startTime\":\"").append(ticketFields[5]).append("\",");
            jsonResponse.append("\"endTime\":\"").append(ticketFields[6]).append("\",");
            jsonResponse.append("\"takeoffStation\":\"").append(ticketFields[7]).append("\",");
            jsonResponse.append("\"arrivalStation\":\"").append(ticketFields[8]).append("\",");
            jsonResponse.append("\"boardingTime\":\"").append(ticketFields[9]).append("\",");
            jsonResponse.append("\"position\":\"").append(ticketFields[10]).append("\"");
            jsonResponse.append("}");
            if (i < resultTickets.size() - 1) {
                jsonResponse.append(",");
            }
        }
        jsonResponse.append("]}");

        out.print(jsonResponse.toString());
        out.flush();
    }
}